//
//  TDNotificationViewController.m
//  TFB
//
//  Created by yull on 15/8/15.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "TDNotificationViewController.h"
#import "TDNotificationDetailViewController.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"
#import "UIWebView+BlocksKit.h"

@interface TDNotificationViewController () <UIWebViewDelegate>

@property (nonatomic, strong) NSMutableArray *notifications;
@property (nonatomic, assign) NSInteger start;
@property (nonatomic, strong) NSString *lastId;
@property (nonatomic, strong) NSMutableDictionary *webHeightDic;

@end

@implementation TDNotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.title = @"公告";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.notifications = [NSMutableArray array];
    self.webHeightDic = [NSMutableDictionary dictionary];
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    __weak typeof(self) wself = self;
    [self.tableView nd_addPullToRefreshWithActionHandler:^(id sender) {
        wself.start = 0;
        wself.lastId = nil;
        [wself loadData];
    }];
    
    [self.tableView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        [wself loadData];
    }];
    
    [self loadData];
}

- (void)clearAppBadge
{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedDescending) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIApplication *app = [UIApplication sharedApplication];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    } else {
        UIApplication *app = [UIApplication sharedApplication];
        
        [app registerForRemoteNotificationTypes:
         (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                    UIRemoteNotificationTypeBadge |
                                    UIRemoteNotificationTypeSound)];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"IconBadgeNumber"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)loadData
{
    [TDHttpEngine requestFor_NOTICE_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                    custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                         start:self.start
                                      pageSize:10
                                        lastId:self.lastId
                                      complete:^(BOOL succeed, NSString *msg, id reqBody) {
                                          [self.tableView nd_endLoadMore];
                                          [self.tableView nd_endRefreshing];
                                          if (succeed) {
                                              
                                              [self clearAppBadge];
                                              
                                              NSArray *list = [reqBody objectForKey:@"noticeList"];
                                              
                                              if (self.start == 0) {
                                                  [self.notifications removeAllObjects];
                                              }
                                              
                                              [self.notifications addObjectsFromArray:list];
                                              
                                              if (self.start == 0 && self.notifications.count) {
                                                  NSDictionary *dic = self.notifications.firstObject;
                                                  if ([dic objectForKey:@"notificeId"]) {
                                                      [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"notificeId"] forKey:@"NOTICELASTID"];
                                                      [[NSUserDefaults standardUserDefaults] synchronize];
                                                  }
                                              }
                                              
                                              [self.tableView reloadData];
                                              
                                              self.start += list.count;
                                              
                                              NSDictionary *dic = self.notifications.lastObject;
                                              if (dic) {
                                                  self.lastId = [dic objectForKey:@"notificeId"];
                                              }
                                              
                                              if (list.count < 10) {
                                                  ((NDRefreshLoadMoreContentView *)(self.tableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                                              } else {
                                                  ((NDRefreshLoadMoreContentView *)(self.tableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                                              }
                                          } else {
                                              [self.view makeToast:msg duration:2.0f position:@"Center"];
                                          }
                                      }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews
{
    // iOS 7
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    // iOS 8
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
    NSString *content = [noticeDic objectForKey:@"noticeBody"];
    if (![content isKindOfClass:[NSString class]]) {
        content = @"";
    }
    
    CGSize size = [content sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(SVFS.width - 20, 54) lineBreakMode:NSLineBreakByTruncatingTail];
    
//    CGFloat height = [[self.webHeightDic objectForKey:@(indexPath.row)] floatValue];
    
    return 50 + (size.height > 54 ? 54 : size.height);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.notifications.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"TransactionQueryIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
        UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, SVFS.width - 20, 20)];
        titleL.font = [UIFont systemFontOfSize:17];
        titleL.tag = 1001;
        [cell.contentView addSubview:titleL];
        
        UILabel *contentL = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleL.frame) + 3, SVFS.width - 20, 0)];
        contentL.font = [UIFont systemFontOfSize:15];
        contentL.numberOfLines = 3;
        contentL.tag = 1002;
        [cell.contentView addSubview:contentL];
        
//        UIWebView *contentW = [[UIWebView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleL.frame) + 3, SVFS.width - 20, 1)];
//        contentW.scrollView.scrollEnabled = NO;
//        contentW.delegate = self;
//        contentW.userInteractionEnabled = NO;
//        contentW.tag = 1002;
//        [cell.contentView addSubview:contentW];
        
        UILabel *timeL = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleL.frame) + 3, SVFS.width- 20, 20)];
        timeL.font = [UIFont systemFontOfSize:14];
        timeL.textColor = [UIColor lightGrayColor];
        timeL.tag = 1003;
        [cell.contentView addSubview:timeL];
    }
    
    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
    NSString *title = [noticeDic objectForKey:@"noticeTitle"];
    if (![title isKindOfClass:[NSString class]]) {
        title = @"--";
    }
    
    NSString *content = [noticeDic objectForKey:@"noticeBody"];
    if (![content isKindOfClass:[NSString class]]) {
        content = @"--";
    }
    
    NSString *time = [noticeDic objectForKey:@"createDate"];
    if (![time isKindOfClass:[NSString class]]) {
        time = @"--";
    } else {
        time = [NSString stringWithFormat:@"%@月%@日 %@:%@:%@",
                [time substringWithRange:NSMakeRange(4, 2)],
                [time substringWithRange:NSMakeRange(6, 2)],
                [time substringWithRange:NSMakeRange(8, 2)],
                [time substringWithRange:NSMakeRange(10, 2)],
                [time substringWithRange:NSMakeRange(12, 2)]];
    }
    
    UILabel *titleL = (UILabel *)[cell.contentView viewWithTag:1001];
    titleL.text = title;
    UILabel *contentL = (UILabel *)[cell.contentView viewWithTag:1002];
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    contentL.attributedText = attrStr;
//    UIWebView *contentW = (UIWebView *)[cell.contentView viewWithTag:1002];
//    [contentW loadHTMLString:content baseURL:nil];
    UILabel *timeL = (UILabel *)[cell.contentView viewWithTag:1003];
    timeL.text = time;
    
//    if (![self.webHeightDic objectForKey:@(indexPath.row)]) {
//        contentW.bk_didFinishLoadBlock = ^(UIWebView *webView) {
//            
//            NSInteger height = webView.scrollView.contentSize.height > 54 ? 54 : webView.scrollView.contentSize.height;
//            [self.webHeightDic setObject:@(height) forKey:@(indexPath.row)];
//            [self.tableView reloadData];
//        };
//    } else {
//        contentW.bk_didFinishLoadBlock = nil;
//    }
    
//    CGSize size = [contentW sizeThatFits:CGSizeMake(contentW.frame.size.width, 5000)];
    [contentL sizeToFit];
//    if ([self.webHeightDic objectForKey:@(indexPath.row)]) {
//        CGRect frame = contentW.frame;
//        frame.size.height = [[self.webHeightDic objectForKey:@(indexPath.row)] floatValue];
//        contentW.frame = frame;
//    }
    
    CGRect frame = timeL.frame;
    frame.origin.y = CGRectGetMaxY(contentL.frame) + 3;
    timeL.frame = frame;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
    TDNotificationDetailViewController *controller = [[TDNotificationDetailViewController alloc] init];
    controller.noticeDic = noticeDic;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
}

@end
